#include "CString.h"
#include "CFile.h"
#include "WinToLinux.h"
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>

// CString的析构函数  
CFile::~CFile(void)
{

}

// CString的普通构造函
CFile::CFile(void)
{
	cfile_fd = -1;
}

int CFile::Open(CString path, int flag, mode_t mode)
{
	cfile_fd = open(path.GetString(), flag, mode);
	if (cfile_fd == -1) 
	{
		printf("open fail, errno: %d\n", errno);
		return FALSE;
	}
	return TRUE;
}

int CFile::Open(CString path, int flag)
{
	cfile_fd = open(path.GetString(), flag);
	if (cfile_fd == -1)
	{
		printf("open fail, errno: %d\n", errno);
		return FALSE;
	}
	return TRUE;

}

void CFile::Close()const
{
	if (cfile_fd != -1)
		close(cfile_fd);
}

int CFile::Write(unsigned char *data, unsigned int length)
{
	if (write(cfile_fd, data, length) != (ssize_t)length)
	{
		printf("Write: fd %d, Write fail, errno: %d\n", cfile_fd, errno);
		return FALSE;
	}
	return TRUE;
}

int CFile::Read(unsigned char *data, unsigned int length)
{
	if (read(cfile_fd, data, length) == -1)
	{
		printf("Read: fd %d, Read fail, errno: %d\n", cfile_fd, errno);
		return FALSE;
	}
	return TRUE;
}

int CFile::GetLength()const
{
	struct stat stat;
	int ret = fstat(cfile_fd, &stat);
	if (ret == -1)
	{
		printf("GetLengh: fstat fail, errno: %d\n", errno);
	}
	return stat.st_size;
}
